package zijie;

/**
 * 给你一个字符串 s，找到 s 中最长的回文子串。
 *
 *  
 *
 * 示例 1：
 *
 * 输入：s = "babad"
 * 输出："bab"
 * 解释："aba" 同样是符合题意的答案。
 */
public class LongestPalindrome_5_5 {
    public static String longestPalindrome(String s) {
        if(s == null || s.length() == 0) return null;
        if(s.length() == 1) return s;
        String res="";
        for (int i = 0; i < s.length(); i++) {
            String s1 = palindrome(s,i,i);
            String s2 = palindrome(s,i,i+1);
            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;

        }
        return  res;
    }

    private static String palindrome(String s,int l,int r){
        while (l >= 0 && r < s.length() && s.charAt(l)==s.charAt(r)){
            l--;
            r++;
        }
        return s.substring(l + 1, r);
    }

    public  String longestPalindrome2(String s) {
        String res = "";
        if(s == null || s.length()==0) return null;
        if(s.length() == 1) return s;
        for (int i = 0; i < s.length(); i++) {
            String s1 = build(s, i, i);
            String s2 = build(s, i, i + 1);
            res = res.length() > s1.length() ? res : s1;
            res = res.length() > s2.length() ? res : s2;
        }
        return res;

    }

    public String build(String s, int l, int r){
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)){
            l--;
            r++;
        }
        return s.substring(l+1,r);
    }



    public static void main(String[] args) {
        String test = "babad";
        String s = longestPalindrome(test);
        System.out.println(s);
    }
}
